#! /usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
import logging
import math
import time

from src.error import ActionError, TasksError


class Action(object):
    def __init__(self, msg):
        """
        action 规则 delete  update
        """
        self.msg = msg
        self.task_name = None
        self.action = 'delete'
        self.task = None
        self.task_data = None
        self.init()

    def init(self):
        self.task_name = self.msg.split("删除")[1].strip()
        print(self.task_name)
        if self.task_name is None:
            raise ActionError(
                'Action task name is None,if you don\'t send taks name ,you can see log to find the random name')
        if self.action is None:
            raise ActionError('Action action is None')


class Tasks(object):
    def __init__(self, msg, obj):
        """

        """
        self.obj = obj
        self.status = None  # 任务的执行状态
        self.now_year = None
        self.now_month = None
        self.now_day = None
        self.msg = msg
        self.msg_day = None
        self.msg_hour = None
        self.msg_min = None
        self.begin_time = None  # 开始时间
        self.next_time = None  # 下一次时间
        self.cycle = None  # 是否循环 0 否 1 是
        self.cycle_time = None  # 循环时间
        self.last_done_time = None
        self.task_name = None
        self.text = None
        self.actual_nick_name = None  # 实际人名称
        self.init_tasks()

    def init_tasks(self):
        """
        每天 几点几分 提醒 干什么
        :return:
        """
        self.begin_time = self.obj["CreateTime"]
        self.now_year = time.localtime(self.obj["CreateTime"]).tm_year
        self.now_month = time.localtime(self.obj["CreateTime"]).tm_mon
        self.now_day = time.localtime(self.obj["CreateTime"]).tm_mday
        self.msg_day = self.msg.split(" ")[0].strip()
        self.msg_hour = self.msg.split(" ")[1].strip().split("点")[0].strip()
        self.msg_min = self.msg.split(" ")[1].strip().split("点")[1].split("分")[
            0].strip()
        self.text = self.msg.split(" ")[3].strip()
        self.change_str_to_time()

        self.task_name = self.random_tasks_name()
        self.actual_nick_name = self.obj["ActualNickName"]

    def change_str_to_time(self):
        one_day = 86400  # 一天多少秒
        time_dict = {
            "每天": 1,
            "明天": 1,
            "后天": 2,
            "大后天": 3,
        }
        if self.msg_day in time_dict.keys():
            self.cycle_time = time_dict.get(self.msg_day) * one_day
            next_time = f"{self.now_year}-{self.now_month}-{self.now_day} {self.msg_hour}:{self.msg_min}:00"
            next_time_ = time.mktime(
                time.strptime(next_time, "%Y-%m-%d %H:%M:%S"))
            if next_time_ - self.begin_time > 0:
                self.next_time = next_time_
            else:
                self.next_time = next_time_ + self.cycle_time
        else:
            mon_ = self.msg_day.split("月")[0].strip()
            day_ = self.msg_day.split("月")[1].strip().split("号").strip()
            next_time = f"{self.now_year}-{mon_}-{day_} {self.msg_hour}:{self.msg_min}:00"
            next_time_ = time.mktime(
                time.strptime(next_time, "%Y-%m-%d %H:%M:%S"))
            if next_time_ - self.begin_time > 0:
                self.next_time = next_time_
            else:
                return TasksError("时间输入有误")
        del_time = self.next_time - self.begin_time
        self.del_hour = math.floor(del_time / 60 / 60)
        self.del_min = math.floor(del_time / 60 % 60)
        if self.msg_day == "每天":
            self.cycle = '1'
        else:
            self.cycle = '0'

    def random_tasks_name(self):

        import random, string
        src = string.digits
        list_ = random.sample(src, 4)
        random.shuffle(list_)
        str_ = ''.join(list_)
        return str_

    def update(self, data):
        self.msg.update(data)

        self.init_tasks()

    def __str__(self):
        return '{}'.format(self.msg)



async def tasks_cycle(future, Tasks_obj):
    """data:{}

    """
    # todo 1。按照时间来计算 sleep 几秒。
    # todo 2。按照是否循环 来判断，future.set_result() 传入的是done 还是 更改后的Tasks
    logging.info('tasks cycle begin >>>>')
    time_now = time.time()
    delt_time = Tasks_obj.next_time - time_now
    sleep_time = delt_time if delt_time >= 0 else 0
    print(sleep_time, "sleep_time")
    Tasks_obj.next_time = Tasks_obj.next_time + Tasks_obj.cycle_time
    logging.info('{} now_time>>>:{}   next_time>>>:{}'.format(
        Tasks_obj.task_name if Tasks_obj.task_name else Tasks_obj.msg,
        time_now, Tasks_obj.next_time))
    await asyncio.sleep(sleep_time)
    try:
        msg = "@{} {}".format(Tasks_obj.actual_nick_name, Tasks_obj.text)
        for i in range(5):
            Tasks_obj.obj.user.send(msg)
            await asyncio.sleep(8)
        Tasks_obj.status = True
        logging.info('Tasks   had    done >>>>>')
    except Exception as e:
        logging.info(e)
        Tasks_obj.cycle = 0
        Tasks_obj.status = False
    finally:
        # todo 执行写入数据库操作。
        future.set_result(Tasks_obj)
